package UI.Main;


import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.net.Socket;

/**
 * @author 杨明政
 * @version  2021.0601
 * @since 1.8
 */


/**
  * 文件发送端类.
  * For example:
  * <pre>
  * FileTransferClient cli = new FileTransferClient(ip,port);
  * cli.sendFile(aim);
  * </pre>
  *
  * @author 杨明政
  * @see java.net.Socket
  */

public class FileTransferClient extends Socket {
    
    private static String SERVER_IP;// 接收端IP
    private static int SERVER_PORT; // 接收端端口
    private Socket client;
    private FileInputStream fis;
    private DataOutputStream dos;
    public String TransURl;
    /**
     * 构造函数
     * 与程序接收端建立连接
     * @param IP 接收端ip
     * @param port 端口号
     * @throws Exception 连接异常
     */
    public FileTransferClient(String IP,int port) throws Exception {
        super(IP, port);
        this.client = this;
        System.out.println("Cliect[port:" + client.getLocalPort() + "] 成功连接服务端");
    }
    
    /**
     * 向服务端传输文件
     * @param aim 发送的文件路径
     * @throws Exception 传输异常
     */
    public void sendFile(String aim) throws Exception {
        try {
            File file = new File(aim);
            if(file.exists()) {
                fis = new FileInputStream(file);
                dos = new DataOutputStream(client.getOutputStream());
                
                // 文件名和长度
                dos.writeUTF(file.getName());
                dos.flush();
                dos.writeLong(file.length());
                dos.flush();
                
                // 开始传输文件
                System.out.println("开始传输文件");
                byte[] bytes = new byte[1024];
                int length = 0;
                long progress = 0;
                while((length = fis.read(bytes, 0, bytes.length)) != -1) {
                    dos.write(bytes, 0, length);
                    dos.flush();
                    progress += length;
                    System.out.print("| " + (100*progress/file.length()) + "% |");
                }
                System.out.println();
                System.out.println("文件传输成功");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if(fis != null)
                fis.close();
            if(dos != null)
                dos.close();
            client.close();
        }
    }

}
